<template>
  <!-- 生产报工单表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    :width="props.width"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120">
      <el-row v-if="props.state == '1'">
        <el-col :span="24">
          <el-form-item label="调整后报工数量" prop="newProductQuantity">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.newProductQuantity"
              placeholder="请输入调整后报工数量"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="formTable" v-if="props.state == '2'">
        <el-table
          :data="formData.details"
          style="width: 100%"
          :key="Math.random"
          border
        >
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="100"
          />
          <!--<el-table-column
            label="周转码"
            props="produceTransferFormCode"
            min-width="150"
          >
            <template #default="{ row }">
              <el-form-item
                :prop="'details.' + $index + '.produceTransferFormCode'"
                label-width="0"
              >
                <span>{{ row.produceTransferFormCode }}</span>
              </el-form-item>
            </template>
          </el-table-column>-->
          <!--<el-table-column label="工作中心" props="workCenterCode" min-width="150">
            <template #default="{$index,row}">
              <el-form-item :prop="'details.' + $index + '.workCenterCode'"  label-width="0">
                <span>{{row.workCenterCode}}</span>
              </el-form-item>
            </template>
          </el-table-column>-->
          <el-table-column
            label="存货编码"
            props="materialCode"
            min-width="150"
          >
            <template #default="{ row }">
              <span>{{ row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            props="productQuantity"
            min-width="150"
            header-align="center"
            align="right"
          >
            <template #default="{ row }">
              <span>{{ row.productQuantity }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="是否合格"
            props="isValid"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <span v-if="row.isValid == 1">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
          <el-table-column
            label="数量单位"
            props="quantityUnit"
            min-width="150"
          >
            <template #default="{ row }">
              <span>{{
                useDictionary("MeasurementUnit", row.quantityUnit)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="调整人" props="adjustsUser" min-width="150">
            <template #default="{ row }">
              <span>{{ row.adjustsUser }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="调整后数量"
            props="adjustsQuantity"
            min-width="150"
            header-align="center"
            align="right"
          >
            <template #default="{ row }">
              <span>{{ row.adjustsQuantity }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="调整时间"
            props="adjustsTime"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <span>{{ row.adjustsTime }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly && props.state == '1'"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { useDictionary } from "@/utils/useTable";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESPRODUCEREPORTADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  state: {
    type: String,
    default: () => {
      return "";
    },
  },
  width: {
    type: String,
    default: () => {
      return "450";
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  workCenterCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  processId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  materialId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  materialCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  productQuantity: [],
  newProductQuantity: [
    { required: true, message: "请输入", trigger: "blur" },
    { pattern: /^\d{1,18}(\.\d{0,6})?$/, message: "请输入数字" },
  ],
  quantityUnit: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  startTime: [],
  isValid: [],
  completeTime: [],
  totalTime: [],
  totalCost: [],
  matTransferDocument: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  produceBatch: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  version: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  produceReportCode: "",
  produceTransferFormId: "",
  produceTransferFormCode: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  producePlanId: "",
  producePlanCode: "",
  produceOrderId: "",
  produceOrderCode: "",
  routingId: "",
  workingFormId: "",
  workingFormCode: "",
  workSequence: "",
  workCenterId: "",
  workCenterCode: "",
  processId: "",
  materialId: "",
  materialCode: "",
  productQuantity: "",
  quantityUnit: "",
  startTime: "",
  isValid: "",
  completeTime: "",
  totalTime: "",
  totalCost: "",
  matTransferDocument: "",
  produceBatch: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  materialName: "",
  details: [],
  newProductQuantity: "",
  plannedBatchId: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (props.state == "1") {
      const {
        id,
        produceReportCode,
        produceTransferFormId,
        produceTransferFormCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        producePlanId,
        producePlanCode,
        produceOrderId,
        produceOrderCode,
        routingId,
        workingFormId,
        workingFormCode,
        workSequence,
        workCenterId,
        workCenterCode,
        processId,
        materialId,
        materialCode,
        productQuantity,
        quantityUnit,
        startTime,
        isValid,
        completeTime,
        totalTime,
        totalCost,
        matTransferDocument,
        produceBatch,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        materialName,
      } = newVal;
      Object.assign(formData, {
        id,
        produceReportCode,
        produceTransferFormId,
        produceTransferFormCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        producePlanId,
        producePlanCode,
        produceOrderId,
        produceOrderCode,
        routingId,
        workingFormId,
        workingFormCode,
        workSequence,
        workCenterId,
        workCenterCode,
        processId,
        materialId,
        materialCode,
        productQuantity,
        quantityUnit,
        startTime,
        isValid,
        completeTime,
        totalTime,
        totalCost,
        matTransferDocument,
        produceBatch,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        materialName,
      });
      formData.plannedBatchId = newVal.id;
    }
    if (props.state == "2") {
      Object.assign(formData.details, props.data);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.produceReportCode = "";
  formData.produceTransferFormId = "";
  formData.produceTransferFormCode = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.producePlanId = "";
  formData.producePlanCode = "";
  formData.produceOrderId = "";
  formData.produceOrderCode = "";
  formData.routingId = "";
  formData.workingFormId = "";
  formData.workingFormCode = "";
  formData.workSequence = "";
  formData.workCenterId = "";
  formData.workCenterCode = "";
  formData.processId = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.productQuantity = "";
  formData.quantityUnit = "";
  formData.startTime = "";
  formData.isValid = "";
  formData.completeTime = "";
  formData.totalTime = "";
  formData.totalCost = "";
  formData.matTransferDocument = "";
  formData.produceBatch = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.materialName = "";
  formData.details = [];
  formData.newProductQuantity = "";
  formData.plannedBatchId = "";
}

const loading = ref(false);

/** 生产报工单保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      await request({
        url: "/mes/mesproducetransferform/reportingWorkChange",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`调整成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
